﻿using Prism.Commands;
using Prism.Events;
using Prism.Modularity;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using TransformerManager.Shared.Helper.HttpParams;
using TransformerManager.WPF.Common.Helper.Events;
using TransformerManager.WPF.Common.Http;
using TransformerManager.WPF.Common.Http.Service;
using TransformerManager.WPF.Common.Utils;
using TransformerManager.WPF.Common.Views;

namespace TransformerManager.WPF.Main.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly IDialogService _dialogService;
        private readonly IModuleCatalog _moduleCatalog;
        private readonly IEventAggregator _eventAggregator;
        private readonly IUserInfoService _userInfoService;
        private readonly HttpRequest _httpRequest;

        public MainWindowViewModel(
            IRegionManager regionManager,
            IDialogService dialogService,
            IModuleCatalog moduleCatalog,
            IEventAggregator eventAggregator,
            IUserInfoService userInfoService,
            HttpRequest httpRequest)
        {
            _regionManager = regionManager;
            _moduleCatalog = moduleCatalog;
            _eventAggregator = eventAggregator;
            _httpRequest = httpRequest;
            _dialogService = dialogService;
            _userInfoService = userInfoService;

            InitCmd();

            // 订阅来自详情页面的事件信息，用于控制重新加载Xml数据按钮是否可用
            _eventAggregator.GetEvent<ReloadXmlDataEnableEvent>()
                .Subscribe(e => 
                { 
                    IsReloadXmlDataEnable = e;
                });
        }

        #region 方法的定义

        private ObservableCollection<MenuModule> _menuModules
             = new ObservableCollection<MenuModule>();
        public ObservableCollection<MenuModule> MenuModules
        {
            get
            {
                return _menuModules;

            }
            set
            {
                _menuModules = value;

                RaisePropertyChanged();
            }
        }

        private string _realNameEn;
        public string RealNameEn
        {
            get
            {
                return _realNameEn;

            }
            set
            {
                _realNameEn = value;
                RaisePropertyChanged();
            }
        }

        private string _userName;
        public string UserName
        {
            get
            {
                return _userName;

            }
            set
            {
                _userName = value;
                RaisePropertyChanged();
            }
        }

        private bool _isReloadXmlDataEnable = false;
        public bool IsReloadXmlDataEnable 
        {
            get
            {
                return _isReloadXmlDataEnable;

            }
            set
            {
                _isReloadXmlDataEnable = value;
                RaisePropertyChanged();
            }
        }

        #endregion

        #region Command

        public DelegateCommand EditUserInfoCmd { private set; get; }

        public DelegateCommand ModifyPwdCmd { private set; get; }

        public DelegateCommand AboutCmd { private set; get; }

        public DelegateCommand ReloadXmlDataCmd { private set; get; }

        #endregion

        #region 函数定义

        private void InitCmd()
        {
            EditUserInfoCmd = new DelegateCommand(async () =>
            {
                await EditUserInfo();
            });

            ModifyPwdCmd = new DelegateCommand(async () =>
            {
                await ModifyUserPwd();
            });

            AboutCmd = new DelegateCommand(AboutInfo);

            ReloadXmlDataCmd = new DelegateCommand(ReloadXmlData);
        }

        public async void InitData()
        {
            await GetUserInfo();

            InitAppsMenu();
        }

        public void InitAppsMenu()
        {
            foreach (var module in _moduleCatalog.Modules)
            {
                Type type = Type.GetType(module.ModuleType);
                dynamic obj = type.Assembly.CreateInstance(type.FullName, true);

                var iconFontColor = obj.IconFontColor;
                var iconFontText = obj.IconFontText;
                var viewName = obj.ViewName;
                var moduleAuth = obj.ModuleAuth;

                if (moduleAuth.Contains("Admin") && AccountInfo.Roles.Count == 0)
                    continue;

                MenuModules.Add(new MenuModule()
                {
                    ModuleName = module.ModuleName,
                    IconFontColor = iconFontColor,
                    IconFontText = iconFontText,
                    NavigateCommand = new DelegateCommand(() =>
                    {
                        _regionManager.RequestNavigate("ContentRegion", viewName);
                    })
                });
            }
        }

        private async Task ModifyUserPwd()
        {
            string currentPwd = string.Empty;
            string newPwd = string.Empty;
            string confirmPwd = string.Empty;

            _dialogService.ShowDialog("ModifyPwdDialog", r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    currentPwd = r.Parameters.GetValue<string>("CurrentPwd");
                    newPwd = r.Parameters.GetValue<string>("NewPwd");
                    confirmPwd = r.Parameters.GetValue<string>("ConfirmPwd");
                }
                else
                {
                    currentPwd = string.Empty;
                    newPwd = string.Empty;
                    confirmPwd = string.Empty;
                }
            });

            if (string.IsNullOrEmpty(currentPwd) ||
                string.IsNullOrEmpty(newPwd) ||
                string.IsNullOrEmpty(confirmPwd))
            {
                return;
            }

            ModifyPasswordParams modifyPasswordParams = new ModifyPasswordParams()
            {
                UserName = AccountInfo.UserName,
                CurrentPassword = currentPwd,
                NewPassword = newPwd,
                ConfirmedNewPassword = confirmPwd
            };
            // 请求修改密码
            await _userInfoService
                .ModifyPasswordAsync(modifyPasswordParams);
        }

        private async Task EditUserInfo()
        {
            UserBasicParams userInfo = new UserBasicParams()
            {
                UserId = AccountInfo.UserId,
                UserName = AccountInfo.UserName,
                RealNameCn = AccountInfo.RealNameCn,
                RealNameEn = AccountInfo.RealNameEn,
                Department = AccountInfo.Department,
                IsLeadEngineer = AccountInfo.IsLeadEngineer,
                Roles = AccountInfo.Roles
            };
            DialogParameters dialogParams = new DialogParameters() { { "UserInfo", userInfo } };

            _dialogService.ShowDialog("UserInfoDialog", dialogParams, r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    userInfo = r.Parameters.GetValue<UserBasicParams>("CurrentUserInfo");
                }
                else
                {
                    userInfo = null;
                }
            });

            if (userInfo == null) return;

            // 请求修改用户信息
            var result = await _userInfoService.ModifyUserInfoAsync(userInfo);

            if (result == null) return;

            // 更新AccountInfo信息
            AccountInfo.RealNameCn = userInfo.RealNameCn;
            AccountInfo.RealNameEn = userInfo.RealNameEn;
            AccountInfo.Department = userInfo.Department;
            AccountInfo.IsLeadEngineer = userInfo.IsLeadEngineer;
        }

        private void AboutInfo()
        {
            _dialogService.ShowDialog("AboutDialog");
        }

        private async Task GetUserInfo()
        {
            // 请求用户信息
            var result = await _userInfoService
                .GetUserInfoByUserNameAsync(AccountInfo.UserName);

            if (result == null) return;

            // 记录用户信息
            AccountInfo.UserId = result.UserId;
            AccountInfo.RealNameEn = result.RealNameEn;
            AccountInfo.RealNameCn = result.RealNameCn;
            AccountInfo.IsLeadEngineer = result.IsLeadEngineer;
            AccountInfo.Department = result.Department;
            AccountInfo.Roles = (IList<string>)result.Roles;

            RealNameEn = AccountInfo.RealNameEn;
        }

        private void ReloadXmlData()
        {
            List<string> reloadXmlTabNames = new List<string>();
            _dialogService.ShowDialog("ReloadXmlDataOptionsDialog", r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    reloadXmlTabNames = 
                        r.Parameters.GetValue<List<string>>("ReloadXmlTabNames");
                }
            });

            foreach(var tabName in reloadXmlTabNames)
            {
                _eventAggregator.GetEvent<ReloadXmlDataPageEvent>()
                    .Publish(tabName);
            }

        }

        #endregion

    }
}
